package com.xbjtech.util;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class SmsUtils {

	public static boolean sendSms(String mobile, String template, Map<String, String> args) {
		try {
			HttpClient client = new HttpClient();
			PostMethod post = new PostMethod("http://api.sms.cn/sms/");
			post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");// 在头文件中设置转码
			NameValuePair[] data = { 
					new NameValuePair("ac", "send"), 
					new NameValuePair("uid", "leejun"),
					new NameValuePair("pwd", "3fae76d636a0adeb597b41d31959624e"),
					new NameValuePair("mobile", mobile), 
					new NameValuePair("template", template),
					new NameValuePair("content", JSON.toJSONString(args)) };
			post.setRequestBody(data);
			client.executeMethod(post);
			int statusCode = post.getStatusCode();
			System.out.println("statusCode:" + statusCode);
			String result = new String(post.getResponseBodyAsString().getBytes("utf-8"));
			System.out.println(result); // 打印返回消息状态
			
			JSONObject jsonObject = JSON.parseObject(result);
			if ("100".equals(jsonObject.getString("stat"))) {
				return true;
			}
			post.releaseConnection();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

}
